import 'dart:typed_data';
import 'dart:convert';
import 'package:encrypt/encrypt.dart';
import 'package:crypto/crypto.dart';
import 'package:hex/hex.dart';

class UtilsHelp {
  Uint8List keyHex = Uint8List.fromList([
    0x61,
    0x3e,
    0x29,
    0xbc,
    0xda,
    0x52,
    0x58,
    0x45,
    0x1e,
    0xbb,
    0x1c,
    0x62,
    0xe2,
    0xa5,
    0xf6,
    0xcb
  ]);
  Uint8List ivHex = Uint8List.fromList([
    0xd7,
    0xe3,
    0x85,
    0xa5,
    0xed,
    0x77,
    0xa2,
    0x6f,
    0x7f,
    0x0d,
    0xd5,
    0xd7,
    0x5a,
    0x70,
    0x3b,
    0x47
  ]);

  static Uint8List processingDataPack(Uint8List originalData, Uint8List key,
      Uint8List iv, int opcode, int flag) {
    int len = originalData.length + 1;
    Uint8List bytes = Uint8List.fromList([len, opcode]);
    Uint8List plainData = Uint8List(2 + originalData.length);

    plainData.setAll(0, bytes);
    plainData.setAll(2, originalData);
    Uint8List encryptData = AES128EncryptWithKey(plainData, key, iv);
    int elen = encryptData.length;
    if (elen > 250) {
      // Handle the case where elen is greater than 250 if needed
    }
    //和校验
    int sum = sumCheck(plainData);
    Uint8List eBytes = Uint8List.fromList([0x55, 0xaa, elen, sum, 0x08]);
    Uint8List cmd = Uint8List(5 + encryptData.length);
    cmd.setAll(0, eBytes);
    cmd.setAll(5, encryptData);
    return cmd;
  }

/*AES加密*/
  static Uint8List AES128EncryptWithKey(
      Uint8List data, Uint8List key, Uint8List iv) {
    int addLen = 16 - data.length % 16;
    Uint8List paddedData = Uint8List(addLen + data.length);
    if (addLen != 0) {
      paddedData.setAll(0, data);
      paddedData.setRange(
          data.length, paddedData.length, List<int>.filled(addLen, 0));
    }
    final encrypter =
        Encrypter(AES(Key(key), mode: AESMode.cbc, padding: null));
    final encrypted = encrypter.encryptBytes(paddedData, iv: IV(iv));
    return Uint8List.fromList(encrypted.bytes);
  }

/*AES解密*/
  static Uint8List AES128DecryptWithKey(
      Uint8List data, Uint8List key, Uint8List iv) {
    String hexString = HEX.encode(data);
    final encrypter =
        Encrypter(AES(Key(key), mode: AESMode.cbc, padding: null));
    final decryptedText = encrypter.decrypt16(hexString, iv: IV(iv));
    Uint8List uint8List = Uint8List.fromList(utf8.encode(decryptedText));
    return uint8List;
  }

/*MD5*/
  static String hashMD5(String input) {
    String md5Hash = md5.convert(utf8.encode(input)).toString();
    return md5Hash;
  }

  static int sumCheck(Uint8List data) {
    int length = data.length;
    int sum = 0;
    for (int i = 0; i < length; i++) {
      sum += data[i];
      if (sum > 255) {
        sum &= 0xFF; // Overflow at 256, keep only the lowest 8 bits
      }
    }
    return sum;
  }
}
